package com.jaws.core.common.initialize;

import com.google.common.collect.Maps;
import com.jaws.core.common.util.WebUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.SpringApplicationRunListener;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.context.ApplicationListener;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.event.ApplicationEventMulticaster;
import org.springframework.context.event.SimpleApplicationEventMulticaster;
import org.springframework.core.Ordered;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.MapPropertySource;

import java.util.List;
import java.util.Map;

/**
 * 框架初始化初始化<br/>
 * 扩展boot增加ip变量，支持获取本机ipv4,ipv6(jaws.ipv4,jaws.ipv6,多网卡下按ip升序排序，只取第一个）<br/>
 *
 * @author maojian
 * @date 2018-04-18 14:38:23
 * @since v1.0.0
 */
@ConditionalOnClass
@Slf4j
public class JawsBootenvironmentInit implements SpringApplicationRunListener, Ordered {
	private static final String JAWS_EXT = "jaws.ext";

	private SpringApplication application;

	private String[] args;

	private final ApplicationEventMulticaster multicaster;

	public JawsBootenvironmentInit(SpringApplication application, String[] args) {
		this.application = application;
		this.args = args;
		this.multicaster = new SimpleApplicationEventMulticaster();
		for (ApplicationListener<?> listener : application.getListeners()) {
			this.multicaster.addApplicationListener(listener);
		}
	}

	@Override
	public int getOrder() {
		return -1;
	}

	public void started() {
	}

	public void starting() {
	}

	@Override
	public void contextPrepared(ConfigurableApplicationContext context) {

	}

	@Override
	public void contextLoaded(ConfigurableApplicationContext context) {
	}

	@Override
	public void finished(ConfigurableApplicationContext context, Throwable exception) {
	}

	@Override
	public void environmentPrepared(ConfigurableEnvironment environment) {

		// 添加自定义变量到配置
		addCustomConfgVars(environment);
	}

	/**
	 * 添加自定义变量给配置中心
	 *
	 * @param environment Spring boot 环境变量
	 * @author liangqm
	 * @date 2018-05-08 17:59:18
	 * @since v1.0.2
	 */
	private void addCustomConfgVars(ConfigurableEnvironment environment) {
		Map<String, Object> map = Maps.newHashMap();
		List<String> ipv4s = WebUtil.getIpv4s();
		if (!ipv4s.isEmpty()) {
			map.put("jaws.ipv4", ipv4s.get(0));
		}

		List<String> ipv6s = WebUtil.getIpv6s();
		if (!ipv6s.isEmpty()) {
			map.put("jaws.ipv6", ipv6s.get(0));
		}

		MapPropertySource extendMapPropertySource = new MapPropertySource(JAWS_EXT, map);

		environment.getPropertySources().addFirst(extendMapPropertySource);
	}


}
